package com.zhongge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhongge.entity.Region;
import com.zhongge.mapper.RegionMapper;
import com.zhongge.service.IRegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhongge
 * @since 2025-11-09
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {
    @Autowired
    private RegionMapper regionMapper;


    @Override
    public List<Region> getProvinces() {
        return regionMapper.getProvinces();
    }

    @Override
    public List<Region> getCity(Integer provincesId) {
        //创建查询条件对象
        QueryWrapper<Region> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",provincesId);
        return regionMapper.selectList(queryWrapper);
    }

    @Override
    public List<Region> getCounties(Integer cityId) {
        //创建查询条件对象
        QueryWrapper<Region> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",cityId);
        return regionMapper.selectList(queryWrapper);
    }

    //初始化行政区域表
    @Override
    public JsonNode initRegion() throws IOException {
        //地址
        String urlStr =
                "https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key=3bbe50548d1ec11e63ccd70163f93809";
        /**
         * 他的使用和 JDBC 一样：找到地址  打开通道  返回数据
         */
        //找到地址
        URL url = new URL(urlStr);
        //打开通道
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        //设置请方式
        urlConnection.setRequestMethod("GET");
        //返回数据
        InputStream inputStream = urlConnection.getInputStream();

        //最后就是解析数据  服务器返回的是 JSON的数据 需要 装变为Java对象
        //1.创建 JSON 解析器
        ObjectMapper objectMapper = new ObjectMapper();
        //2.将文件(JSON文本)变为JSON对象
        JsonNode jsonNode = objectMapper.readTree(inputStream);

        //开始从这个JSON对象中 将数据解析出来 存入我们的数据库中 此时需要的是相关API的调用

        //获取第一层：省份
        JsonNode provinces = jsonNode.get("districts").get(0).get("districts");

        //循环存储 所有省份
        for (JsonNode province: provinces) {
            String name = province.get("name").asText();
            String adcode = province.get("adcode").asText();
            //保存省份
            Region provinceNode = saveProvince(name,adcode);

            //第二层：获取该省份下的所有城市
            JsonNode cities = province.get("districts");
            //继续循环遍历 保存所有的市州
            for (JsonNode city: cities) {
                String adcode1 = city.get("adcode").asText();
                String name1 = city.get("name").asText();
                //保存市州信息
                Region cityNode =  saveCity(adcode1,name1,provinceNode);

                // 第三层：获取该城市下的所有区县
                JsonNode counties = city.get("districts");
                //循环存储 所有县
                for (JsonNode county:counties) {
                    String adcode2 = county.get("adcode").asText();
                    String name2 = county.get("name").asText();
                    //保存县信息
                    Region countyNode =  saveCounty(adcode2,name2,cityNode);
                }
            }
        }
        return provinces;
    }


    private Region saveCounty(String adcode2, String name2, Region cityNode) {
        Region region = new Region();
        region.setCode(adcode2);
        region.setName(name2);
        region.setParentId(cityNode.getId());
        this.save(region);
        return region;
    }

    private Region saveCity(String adcode1, String name1, Region provinceNode) {
        Region region = new Region();
        region.setCode(adcode1);
        region.setName(name1);
        region.setParentId(provinceNode.getId());
        this.save(region);
        return region;
    }

    private Region saveProvince(String name, String adcode) {
        Region region = new Region();
        region.setName(name);
        region.setCode(adcode);
        this.save(region);
        return region;
    }
}
